 //
//  UIImageView+ZQDownLoad.m
//  BuDeJie
//
//  Created by zuqiu on 2018/3/21.
//  Copyright © 2018年 zuqiu. All rights reserved.
//

#import "UIImageView+ZQDownLoad.h"
#import <AFNetworking/AFNetworking.h>

#import "UIImage+Image.h"
@implementation UIImageView (ZQDownLoad)
- (void)zq_setOriginImage:(NSString *)originImageURL AndThumbnailImage:(NSString *)thumbnailImageURL placeholderImage:(UIImage *)placeholderImage completed:(SDExternalCompletionBlock)completedBlock
{
    // 根据网络情况显示加载图片
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 获得原图
    UIImage *originImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:originImageURL];
    if (originImage) {
        self.image = originImage;
        completedBlock(originImage,nil,0,[NSURL URLWithString:originImageURL]);
    } else {  // 原图未下载
        if (mgr.isReachableViaWiFi) {
            [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholderImage  completed:completedBlock];
        } else if (mgr.isReachableViaWWAN) {
            [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImageURL] placeholderImage:placeholderImage completed:completedBlock];
        } else { // 没网
            // 缩略图
            UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:thumbnailImageURL];
            if (thumbnailImage) { // 缩略图被下载过
                self.image = thumbnailImage;
                completedBlock(thumbnailImage,nil,0,[NSURL URLWithString:thumbnailImageURL]);
            } else {
                //显示占位图
                self.image = placeholderImage;
            }
        }
    }
}


- (void)zq_setHeadImage:(NSString *)headImageURL
{
    // 设置圆形图片 SDWebImageCacheMemoryOnly 缓存到内存，0 代表沙盒节省流量
    
    [self sd_setImageWithURL:[NSURL URLWithString:headImageURL] placeholderImage:[UIImage zq_circleImageNamed:@"defaultUserIcon"]  options:0 completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!image)  return ;
        self.image = [image zq_circleImage];
    }];
}
@end
